package org.tinygame.herostory.mq;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author anan
 * @create 2022-05-08 15:18
 */
public final class MqProducer {

    static private final Logger LOGGER = LoggerFactory.getLogger(MqProducer.class);

    static private DefaultMQProducer _producer = null;

    private MqProducer() {
    }

    /**
     * 初始化
     */

    static public void init() {
        try {
            DefaultMQProducer producer = new DefaultMQProducer(" ");
            producer.setNamesrvAddr("127.0.0.1:9876");
            producer.start();
            producer.setRetryTimesWhenSendAsyncFailed(3);

            _producer = producer;
            LOGGER.info("消息队列（生产者）连接成功");
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /**
     * 发送消息
     */

    static public void sendMsg(String topic, Object msg) {
        if (null == topic || null == msg) return;

        Message newMsg = new Message();
        newMsg.setTopic(topic);
        newMsg.setBody(JSONObject.toJSONBytes(msg));

        try {
            _producer.send(newMsg);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}
